package controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import utils.PasswordEncrypt;
import database.ReadDAO;
import database.WriteDAO;

/**
 * Servlet implementation class RegistrationController
 */
public class RegistrationController extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public RegistrationController() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected synchronized void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		WriteDAO writedao = new WriteDAO();
		ReadDAO readdao = new ReadDAO();
		String encryptedpassword = "";

		String voornaam = request.getParameter("voornaam");
		String achternaam = request.getParameter("achternaam");
		String inlognaam = request.getParameter("inlognaam");
		String wachtwoord = request.getParameter("password");

		// inlognaam mag nog niet bestaan
		if(readdao.getInlognaamExists(inlognaam)){
			request.setAttribute("Veilingen", readdao.getVeilingen());
			request.setAttribute("error", "usernameexists");
			RequestDispatcher view = request.getRequestDispatcher("/WEB-INF/errorpages/error.jsp");
			view.forward(request, response);
			return;
		}

		try {
			encryptedpassword = PasswordEncrypt.getInstance().encrypt(wachtwoord);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(voornaam.equals("") || achternaam.equals("") || inlognaam.equals("") || wachtwoord.equals("")){
			request.setAttribute("error", "emptyfieldsregister");
			RequestDispatcher view = request.getRequestDispatcher("/WEB-INF/errorpages/error.jsp");
			view.forward(request, response);
			return;
		}else{

			writedao.addGebruiker(voornaam, achternaam, inlognaam, encryptedpassword);


			response.sendRedirect("./VeilingController");
		}
	}

}
